import { loginApi, getUserInfoApi, getUserDetailByidApi } from '@/api/user'
import { resetRouter } from '@/router'
export default {
  namespaced: true,
  state: {
    token: null, // 存token
    userInfo: null, // 用户信息
    hrsaasTime: 0 // 保存登录时候的时间戳
  },
  mutations: {
    // 设置token
    setToken(state, token) {
      state.token = token
    },
    // 移除token
    removeToken(state) {
      state.token = null
    },
    // 设置用户资料
    setUserInfo(state, userInfo) {
      state.userInfo = userInfo
    },
    // 移除用户资料
    removeUserInfo(state) {
      state.userInfo = null
    },
    // 设置点击登录时候的时间戳
    setHrsaasTime(state, time) {
      state.hrsaasTime = time
    }
  },
  actions: {
    // 发请求拿token
    async loginAction({ commit }, data) {
      const token = await loginApi(data)
      // 操作mutations方法存储token
      commit('setToken', token)
      commit('setHrsaasTime', Date.now())
    },

    // 发请求拿用户信息
    async getUserInfoAction({ commit }) {
      const res = await getUserInfoApi()
      const res1 = await getUserDetailByidApi(res.userId)
      commit('setUserInfo', { ...res, ...res1 })
    },

    // 退出登录
    logout({ commit }) {
      // 清除用户信息
      commit('removeToken')
      commit('removeUserInfo')
      // 退出之后重置路由
      resetRouter()
    }
  }
}
